//
//  SignView.swift
//  SBSafetyApp
//
//  Created by Lina on 2022/11/16.
//

import Foundation
import UIKit
import MaLiang

class SignView: UIView {
    
    let canvas = Canvas(frame: CGRect(x: 0, y: 0, width: ScreenHeight, height: ScreenWidth - 80))
    let saveBtn = UIButton.createPrimaryLarge("完成签名")
    let clearBtn = UIButton.createDefaultLarge("清除签名")

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        if let nickName = BSUser.currentUser.nickName {
            canvas.addWaterText(text: nickName)
        }
        
        canvas.data.addObserver(self)
        addSubview(canvas)
        
        addSubview(clearBtn)
        clearBtn.snp.makeConstraints { make in
            make.left.equalTo(self.snp.left).offset(16)
            make.bottom.equalTo(self.snp.bottom)
            make.width.equalTo(ScreenWidth - 48)
            make.height.equalTo(50)
        }
        
        addSubview(saveBtn)
        saveBtn.snp.makeConstraints { make in
            make.left.equalTo(clearBtn.snp.right).offset(16)
            make.bottom.equalTo(self.snp.bottom)
            make.right.equalTo(self.snp.right).offset(-16)
            make.height.equalTo(50)
        }
    }
}

extension SignView: DataObserver {

    public func lineStrip(_ strip: LineStrip, didBeginOn data: CanvasData) {}
    
    /// called when a element is finished
    public func element(_ element: CanvasElement, didFinishOn data: CanvasData) {}
    
    /// callen when clear the canvas
    public func dataDidClear(_ data: CanvasData) {}
    
    /// callen when undo
    public func dataDidUndo(_ data: CanvasData) {}
    
    /// callen when redo
    public func dataDidRedo(_ data: CanvasData) {}
}

// 水印
extension UIView {
    func addWaterText(text: String, color:UIColor = .ccc, font:UIFont = UIFont.systemFont(ofSize: 15, weight: .light)) {
        let sublay = CALayer()
        sublay.transform = CATransform3DMakeRotation(CGFloat(-Double.pi / 16), 0, 0, 3)
        self.layer.insertSublayer(sublay, at: 0)

        let textSize:CGSize = text.sizeWithText(font: font)
        let height = UIScreen.main.bounds.size.height
        let line:NSInteger = Int(height*3.5)%80
        let row:NSInteger = 20
        let lineSpace:Int = Int(textSize.width + 30)
        let rowHeight:Int = Int(textSize.width+40)
        let textWidth:Int = Int(textSize.width)
        let textHeight:Int = Int(textSize.height)
        for i in  0...line {
            for j in 0...row
            {
                let textLayer = CATextLayer.init()
                textLayer.contentsScale = UIScreen.main.scale
                textLayer.font = font
                textLayer.fontSize = font.pointSize
                textLayer.foregroundColor = color.cgColor
                textLayer.string = text
                let hSpace : Int = j*lineSpace
                let vSpace : Int = i * rowHeight
                
                textLayer.frame = CGRect(x: hSpace, y: vSpace, width: textWidth , height: textHeight)
             
                textLayer.transform = CATransform3DMakeRotation(CGFloat(-Double.pi / 16), 0, 0, 3)
                sublay.addSublayer(textLayer)
            }
        }
    }
    
    func removeTextLayer(water:String)  {
        let layers = self.layer.sublayers
        var sublayers = [CALayer]()
        
        for (idx,layer) in (layers?.enumerated())! {
            
            if layer .isKind(of: CATextLayer.self) {
                let textLayer = layer as!CATextLayer
                
                let waterText:String = textLayer.string as! String
                
                guard water == waterText else {
                    return
                }
                
            }else{
                sublayers.append(layer)
            }
           
            
            print(layer.frame,idx)
        }
        self.layer.sublayers = sublayers
    }
}

extension String {
    func sizeWithText(font: UIFont) -> CGSize {
        let attributes = [NSAttributedString.Key.font: font]
        let option = NSStringDrawingOptions.usesLineFragmentOrigin
        let rect:CGRect = self.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: option, attributes: attributes, context: nil)
        return rect.size;
    }
}
